package Thread;
/**synchronized 修饰方法*/

class Counter {
    private int count = 0;

//    synchronized public void add() {
//        count++;
//    } // 与下面的等价

    public void add() {
        synchronized (this) {
            count++;
        }
    }

    public int get() {
        return count;
    }

    // 特殊的情况：static修饰的方法
    // static修饰的方法没有this,当 synchronized 修饰 static 方法
    // 相当于针对类对象加锁
    // 类对象：反射时讲的
    public synchronized static void func() {
        synchronized (Counter.class) {

        }
    }
}


public class demo18 {
    public static void main(String[] args) throws InterruptedException {
        // StringBuilder stringBuilder; 这些对象，方法上带有synchronized（针对this进行加锁）
        Object locker = new Object();
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                // synchronized (locker) {
                counter.add();
                // }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                // synchronized (locker) {
                counter.add();
                // }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count=" + counter.get());
    }
}
